package com.collectplus.express.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * 自动换行
 * 
 * @author coffee<br>
 *         2015-10-20下午7:13:10
 */
public class AutoNextLineViewGroup extends ViewGroup {
	private final String TAG = AutoNextLineViewGroup.class.getSimpleName();

	public AutoNextLineViewGroup(Context context) {
		super(context);
	}

	public AutoNextLineViewGroup(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
		int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

		int paddingtop = this.getPaddingTop();
		int paddingbottom = this.getPaddingBottom();

		int right = 0;
		int bottom = paddingtop;

		for (int index = 0; index < getChildCount(); index++) {
			final View child = getChildAt(index);
			child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

			int tempButtom = child.getBottom();

			if (tempButtom > bottom) {
				bottom = tempButtom;
			}

			int tempRight = child.getRight();

			if (tempRight > right) {
				right = tempRight;
			}
		}

		setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? sizeWidth : right, (heightMode == MeasureSpec.EXACTLY) ? sizeHeight : bottom + paddingbottom);
	}

	// these four parameters represent the position of this view in parent
	@Override
	protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
		int groupWidth = right - left;
		int paddingleft = this.getPaddingLeft();
		int paddingtop = this.getPaddingTop();
		int paddingright = this.getPaddingRight();

		final int count = getChildCount();

		int lengthX = paddingleft;
		int lengthY = paddingtop;

		int row = 1;// 行数
		for (int index = 0; index < count; index++) {
			View child = getChildAt(index);
			int width = child.getMeasuredWidth() ;
			int height = child.getMeasuredHeight();
			lengthX += width;
			// ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) child.getLayoutParams();
			lengthY = row * height + paddingtop;
			if (lengthX > groupWidth - paddingright) {
				lengthX = width + paddingleft;
				row++;
				lengthY = row * height + paddingtop;
			}
			child.layout(lengthX - width, lengthY - height, lengthX, lengthY);
			lengthX += child.getPaddingLeft() + child.getPaddingRight();
		}
	}
}